package com.example.demo.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {
    //shiroFilterFactoryBean          step3
    //DefaultWebSecurityManager         step2
    //realm对象       step1

    @Bean(name="userRealm")                                  //自己写的类被spring托管
    public UserRealm userRealm(){
        return new UserRealm();
    }

    @Bean(name="getDefaultWebSecurityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
        DefaultWebSecurityManager SecurityManager=new DefaultWebSecurityManager();
        SecurityManager.setRealm(userRealm);
        return SecurityManager;
    }

    @Bean
    public ShiroFilterFactoryBean  shiroFilterFactoryBean(@Qualifier("getDefaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean factoryBean=new ShiroFilterFactoryBean();
        //设置安全管理器
        factoryBean.setSecurityManager(defaultWebSecurityManager);
        //添加shiro的内置过滤器
        /*
        * anon ：无需认证就可以访问
        * authc ：必须认证了才能访问
        * user　：必须拥有　记住我　功能才能用
        * perms:必须拥有对某个资源的权限才能访问
        * role：拥有对某个角色权限才能访问
        * */
        Map<String,String> filterMap=new LinkedHashMap<>();
        //授权，401未授权
        filterMap.put("/user/add","perms[user:add]");
        filterMap.put("/user/update","perms[user:update]");

        //拦截简单请求
        filterMap.put("/user/*","authc");

        factoryBean.setFilterChainDefinitionMap(filterMap);

        //设置登录的请求
        factoryBean.setLoginUrl("/tologin");
        //设置未授权请求
        factoryBean.setUnauthorizedUrl("/401");
        return factoryBean;
    }

    //shiro+thymeleaf,整合shirodialect用thymeleaf+shiro
    @Bean
    public ShiroDialect getShiroDialect(){
        return new ShiroDialect();
    }
}
